//常用功能库  全局对象ZMquery
class MLqueryInit{
	constructor(){
		this.init();
	};
	init(){
	};
	//1 统计字数方法
	countStr(string){
		let result = {};
		for(var i of string){
			// console.log(i)
			if(result[i]){
				result[i]++
			}else{
				result[i]=1;
			}
		}
		return result
	};
	//2 给金额加千位分隔符的函数
	moneyFormat(money){
		if(!(typeof money == 'number') && !(typeof money == 'string')){
			throw new Error('输入错误！')
		}
		if (typeof money == 'number') {
			money=money.toString();
		}
		let integer = money.split('.')[0];
		let decimal = money.split('.')[1] || '';
		// console.log(integer,decimal)
		let integerArr = integer.split('').reverse();
		// console.log(integerArr)
		let tempArr =[];
		for(var i=0;i<integerArr.length;i++){
			tempArr.push(integerArr[i])
			if (i % 3 ==2 && i<integerArr.length-1 ) {
				tempArr.push(',');
			}
		}
		let resultIteger = tempArr.reverse().join('');
		if(decimal){
			decimal = '.' + decimal.toString();
		};
		return resultIteger+decimal
		}
		//3 检测邮箱正确性的方法
		checkMail(email){
			let mailReg =/^([\w\.])+@(\w+)([\.]\w+)+$/;
			return mailReg.test(email);
		};
		//4 深拷贝的方法
		deepClone(params){
			let target = params  instanceof Array ? []:{};
			for(var key in params){
				if (typeof params[key] == 'object') {
					target[key] = deepClone(params[key])
				}else{
					target[key] = params[key];
				}
			}
			return target
		}
		//5 连字符改成托驼峰写法 font-size
		nameFormat(string){
			let tempStr = string.split('');
			if (tempStr[0] == '-') {
				tempStr.splice(0,1);
			};
			tempStr.forEach((item,index)=>{
				if (item == '-') {
					tempStr.splice(index,1);
					tempStr[index] = tempStr[index].toUpperCase();
				}
			})
			return tempStr.join('');
		}
		//6 格式化日期的方法
		dateFormat(date,format='XXXX年MM月DD日 星期Day hh:mm:ss'){
			let config = {
				XXXX:date.getFullYear(),
				MM:date.getMonth()+1,
				DD:date.getDate(),
				hh:date.getHours(),
				mm:date.getMinutes(),
				ss:date.getSeconds(),
				Day:date.getDay() == 0 ? '日':date.getDay()
			};
			for(var key in config){
				format = format.replace(key,config[key])
			}
			return format
		}
		// 7 延时方法
		reqDelayAjax(option,delay=5000){
			let arr =[new Promise((resolve,reject)=>{
				this.promiseAjax(option).then(res=>{
						resolve(res)
					},err=>{
					reject('请求失败！')
				})

			}),new Promise(reject=>{
				setTimeout(()=>{
					reject('请求超时！')
				},delay)
			})];
			return Promise.race(arr)
		};
		// 8. promise封装的ajax
		promiseAjax(option){
			let defaultOption = {
				type:'get',
				url:'',
				data:{},
				header:{
					'content-type':'application/json',
				}
			}
			Object.assign(defaultOption,option);
			return new Promise((resolve,reject)=>{
				// 处理参数data
				let params = '';
				let url = defaultOption.url;
				for(var key in defaultOption.data){
					params += key +'='+ defaultOption.data[key] +'&'
				};
				params = params.slice(0,params.length-1);
				let xhr = new XMLHttpRequest();
				if(defaultOption.type =='get'){
					url += '?'+ params;
					// console.log(url)
					xhr.open(defaultOption.type,url);
				}
				xhr.open(defaultOption.type,url);
				if (defaultOption.type == 'post') {
					let contentType = defaultOption.header['content-type'];
					xhr.setRequestHeader('Content-Type',contentType);
					if (contentType == 'application/json') {
						xhr.send(JSON.stringify(defaultOption.data));
					}
					xhr.send(defaultOption.data);
				}
				xhr.send();
				xhr.onload =function(){
					if (xhr.status==200 && xhr.readyState ==4) {
						let responseText = xhr.responseText;
						if (xhr.getResponseHeader('Content-Type').includes('application/json')) {
							responseText = JSON.parse(responseText);
						}
						return resolve(responseText)
					}
				};
				xhr.onerror = (err)=>{
					reject(err)
				}
			})
		};
		// 9.计时进度条
		progressBar(option,callback){
			let barWap = document.createElement('p');
			barWap.setAttribute('id','barWap');
			barWap.style.width = option.style.width;
			barWap.style.height = option.style.height;
			barWap.style.backgroundColor = option.style.wapBgcolor;
			barWap.style.borderRadius =option.style.borderRadius;
			barWap.style.position = option.style.position;
			barWap.style.left = option.style.left;
			barWap.style.top = option.style.top;
			document.body.appendChild(barWap);
			let inerbar = document.createElement('span');
			inerbar.setAttribute('id','Inerbar');
			inerbar.style.display ='block';
			inerbar.style.height = '100%';
			inerbar.style.backgroundColor = option.style.Bgcolor;
			inerbar.style.borderRadius =option.style.borderRadius;
			inerbar.style.position = 'absolute';
			inerbar.style.left = 0;
			inerbar.style.top =0;
			inerbar.style.color="white";
			inerbar.style.textAlign='center';
			inerbar.style.fontSize = '1vw';
			inerbar.style.lineHeight =  option.style.height;
			inerbar.style.transition='all 0.1s linear';
			barWap.appendChild(inerbar);
			let i =0;
			let seconds = option.seconds;
			(function barRun(){
				inerbar.style.width = i +'%';
				inerbar.innerText=i+'%';
				if (++i<=100) {
					setTimeout(()=>{
						barRun()
					},seconds)
				}
				if (i==100) {
					callback();
				}
			})()
			
		};
		// 10.节点相关操作
		//通过id获取元素
		getNodeById(id){
			return document.getElementById(id);
		};
		// 设置元素css属性
		setCss(id,key,value){
			document.getElementById(id).style[key]=value;
			return this
		};
	   // 设置元素的属性
	    setAttr(id,key,value){
	   	   document.getElementById(id)[key]=value;
	   	   return this
	    };
	    setHtml(id,html){
	    	document.getElementById(id).innerHTML =html;
	    	return this
	    };
	    // 为元素绑定事件
	    bindEvent(id,type,fn){
	    	var dom =document.getElementById(id);
	      (function addEvent(dom,type,fn){
				// 对于支持DOM2级事件处理程序addEventListener方法的浏览器
				if (dom.addEventListener) {
					dom.addEventListener(type,fn,false);
				}else if(dom.attachEvent){
					dom.attachEvent('on'+type,fn);
				}else{
					dom['on'+type]=fn;
				}
			})(dom,type,fn)

	    };
	    //实现去除重复的方法
	    removeAgain(arr){
	    	let res = [];
	    	let flag = true;
	    	arr.forEach((item,index)=>{
	    		if (item != item) {
	    			flag && res.indexOf(item)<0 ? res.push(item) : '';
	    			flag = false;
	    		}else{
	    			res.indexOf(item)<0 ? res.push(item) :'';
	    		}
	    	})
	    	return res
	    }



}





window.MLquery=new MLqueryInit();
